package hashdemo;

import java.util.*;

/**
 * @author tongchen
 * @create 2022-11-17 22:34
 * 测试hashmap和treemap的几种遍历方式
 */
public class Exer2 {
    public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        //添加元素
        hashMap.put(1,"hi");
        hashMap.put(2,"hell0");
        hashMap.put(3,"nihao");
//1.方式1：keySet
        Set<Integer> set = hashMap.keySet();
        for (Integer key:set ) {
            System.out.println(key+" "+hashMap.get(key));

        }
        //方式2：entryset
        Set<Map.Entry<Integer, String>> entries = hashMap.entrySet();
        for (Map.Entry entry:entries) {
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
        //方式3：迭代器
        Iterator<Map.Entry<Integer, String>> iterator = hashMap.entrySet().iterator();
        while(iterator.hasNext()){
            //如果存在就向下遍历
            Map.Entry<Integer,String> entry=iterator.next();
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
        //4.通过values集合
        Collection<String> values = hashMap.values();
        for (String value:values) {
            System.out.println(value);
        }

    }
}
